from django.db.models import F
from rest_framework import serializers, pagination
from rest_framework.response import Response

from .models import Post, Comment
from user.models import User
from user.serializers import UserDetailSerializer


class PostSerializer(serializers.HyperlinkedModelSerializer):
    """
    帖子列表页序列化对象
    """
    url = serializers.HyperlinkedIdentityField(view_name='api:post-detail')
    owner = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.filter(is_active=True))
    owner_image = serializers.ImageField(source='owner.image', read_only=True)

    class Meta:
        model = Post
        fields = ['id', 'url', 'title', 'desc', 'owner', 'owner_image', 'content', 'created_time', 'visitor_count', 'comment_count', 'thumb_up_count']
        read_only_fields = ['created_time', 'visitor_count', 'comment_count', 'thumb_up_count']
        extra_kwargs = {
            'content': {'write_only': True}
        }

    def create(self, validated_data):
        post = Post(title=validated_data['title'], desc=validated_data['desc'], content=validated_data['content'])
        user = User.objects.get(username=validated_data['owner'])
        post.owner = user
        post.save()
        return post


class PostDetailSerializer(serializers.ModelSerializer):
    """
    帖子详情页序列化对象
    """
    owner = serializers.SlugRelatedField(slug_field='username', read_only=True)
    owner_image = serializers.ImageField(source='owner.image', read_only=True)
    comments = serializers.SerializerMethodField('paginated_comments')
    thumbers = serializers.SlugRelatedField(slug_field='username', read_only=True, many=True)

    class Meta:
        model = Post
        fields = ['id', 'title', 'desc', 'owner', 'owner_image', 'content', 'created_time', 'visitor_count', 'comment_count', 'thumb_up_count', 'comments', 'thumbers']
        read_only_fields = ['created_time', 'visitor_count', 'comment_count', 'thumb_up_count']

    def paginated_comments(self, obj):
        comments = obj.comment_set.filter(status=Comment.STATUS_NORMAL)
        paginator = pagination.PageNumberPagination()
        page = paginator.paginate_queryset(comments, self.context['request'])
        serializer = CommentSerializer(page, many=True, context={'request': self.context['request']})
        return {
            'count': comments.count(),
            'results': serializer.data,
            'previous': paginator.get_previous_link(),
            'next': paginator.get_next_link()
        }


class CommentSerializer(serializers.ModelSerializer):
    """
    评论列表页序列化类
    """
    url = serializers.HyperlinkedIdentityField(view_name='api:comment-detail')
    post = serializers.SlugRelatedField(slug_field='id', queryset=Post.objects.filter(status=Post.STATUS_NORMAL))
    owner = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.filter(is_active=True))
    owner_image = serializers.ImageField(source='owner.image', read_only=True)

    class Meta:
        model = Comment
        fields = ['id', 'url', 'post', 'owner', 'owner_image', 'content', 'created_time']
        read_only_fields = ['created_time']

    def create(self, validated_data):
        post = validated_data['post']
        post.comment_count = F('comment_count') + 1
        post.save()
        return super().create(validated_data)


class CommentDetailSerializer(serializers.ModelSerializer):
    """
    评论详情页序列化类
    """
    owner = serializers.SlugRelatedField(read_only=True, slug_field='username')
    owner_image = serializers.ImageField(source='owner.image', read_only=True)

    class Meta:
        model = Comment
        fields = ['id', 'post', 'owner', 'owner_image', 'content', 'created_time']
        read_only_fields = ['created_time']
